package com.wgke.bluetooth.vm;

import android.annotation.SuppressLint;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.google.gson.Gson;
import com.wgke.bluetooth.R;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

public class BaseVM extends ViewModel {

    //加载条设置
    public MutableLiveData<Boolean> isShowLoading = new MutableLiveData<>(false);

    //展示错误的页面
    public MutableLiveData<Boolean> isShowError = new MutableLiveData<>(false);

    //是否展示主布局
    public MutableLiveData<Boolean> isShowContent = new MutableLiveData<>(true);

    //关闭页面的数据监听
    public MutableLiveData<Boolean> isFinishPage = new MutableLiveData<>(false);

    //关闭页面的数据监听
    public MutableLiveData<String> pageTitle = new MutableLiveData<>("");

    //文案提示
    public MutableLiveData<String> loadingText = new MutableLiveData<>("正在加载中...");
    public MutableLiveData<String> errorText = new MutableLiveData<>("无网络连接");

    Gson gson = new Gson();

    Map<String, Float> map = new HashMap<>();
    Map<String, Integer> map2 = new HashMap<>();

    @SuppressLint("SetTextI18n")
    public void createBtn(View v, String type, Object value, Object step, View.OnClickListener listener) {
        Button add = v.findViewById(R.id.btn_add);
        Button cut = v.findViewById(R.id.btn_cut);
        TextView tvType = v.findViewById(R.id.tvType);
        TextView tvValue = v.findViewById(R.id.tvValue);
        if (tvType != null) tvType.setText(type);
        tvValue.setText("" + value);
        if (value instanceof Integer && step instanceof Integer) {
            map2.put(type, (Integer) value);
        } else if (value instanceof Float && step instanceof Float) {
            map.put(type, (Float) value);
        } else {
            throw new RuntimeException("value and step must be same type");
        }
        View.OnClickListener l = v1 -> {
            int dd = v1.getId() == R.id.btn_add ? 1 : -1;
            if (value instanceof Integer) {
                int newValue = map2.get(type) + (Integer) step * dd;
                map2.put(type, newValue);
                tvValue.setText("" + newValue);
                v1.setTag(newValue);
            } else if (value instanceof Float) {
                float newValue = map.get(type) + (Float) step * dd;
                DecimalFormat df = new DecimalFormat("#.##"); // 保留2位小数
                map.put(type, newValue);
                tvValue.setText(df.format(newValue));
                v1.setTag(newValue);
            }
            listener.onClick(v1);
        };
        add.setOnClickListener(l);
        cut.setOnClickListener(l);
    }

}
